package com.liangzong.betspider.task;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import static com.liangzong.betspider.utils.SpiderInfoUtil.*;

@Slf4j
@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
public class RecreateProcessTask {

    @Autowired
    StartSpiderTask startSpiderTask;

    //暂不启用
    //每天上午午5点，12点 0 0 5,12 * * ?
    @Scheduled(cron = "0 0 11 * * ?")
    public void refreshTasks() {
        try {
            List<Process> tempList = new ArrayList<>();
            log.info("执行刷新代理定时任务时间: " + LocalDateTime.now());
            for (Process process : threads) {
                try {
                    int port = process.getPort();
                    int overTime = process.getOverTime();
                    long pauseTime = process.getPauseTime();
                    boolean reverse = process.isReverse();
                    String sessionId = process.getSessionId();
                    boolean b = process.stopWork();
                    if (b) {
                        removeRefreshList(sessionId);
                        Process newProcess = new Process(startSpiderTask, reverse, port, pauseTime, overTime);
                        newProcess.setDaemon(true);
                        newProcess.start();
                        tempList.add(newProcess);
                    }
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
            threads.clear();
            threads.addAll(tempList);
//            clearRefreshList();
//            startSpiderTask.startWorks();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }


}
